package com.dreamer.service.mobile.impl;

import com.dreamer.domain.account.GoodsAccount;
import com.dreamer.domain.mall.goods.Goods;
import com.dreamer.domain.mall.goods.Price;
import com.dreamer.domain.pmall.goods.PmallGoods;
import com.dreamer.domain.user.*;
import com.dreamer.domain.user.enums.AccountsTransferStatus;
import com.dreamer.domain.user.enums.AccountsType;
import com.dreamer.domain.user.enums.AgentLevelEnum;
import com.dreamer.repository.mobile.PriceDao;
import com.dreamer.service.mobile.TransferHandler;
import com.dreamer.repository.mobile.AccountsDao;
import com.dreamer.service.mobile.*;
import com.dreamer.util.PreciseComputeUtil;
import com.dreamer.util.RewardUtil;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ps.mx.otter.exception.ApplicationException;
import java.util.*;

/**
 * Created by huangfei on 02/07/2017.
 */
@Service
public class AccountsHandlerImpl extends BaseHandlerImpl<Accounts> implements AccountsHandler {


    /**
     * 减少账户
     * 生成记录
     *
     * @param
     * @param amount
     */
    public AccountsRecord deductAccountAndRecord(AccountsType accountsType, Agent agent, Agent casedAgent, Double amount, String more) {
        Accounts accounts = agent.getAccounts();
        Double nowAmount = deductAccount(accountsType, accounts, amount);
        AccountsRecord record = new AccountsRecord(agent, casedAgent, accountsType, more, amount, nowAmount, new Date(), AccountsRecord.SUB);
        return record;
    }


    /**
     * 减少账户
     * 生成记录
     *
     * @param
     * @param amount
     */
    public AccountsRecord deductAccountAndRecord(AccountsType accountsType, Agent agent, Agent casedAgent, Double amount, String more, Boolean validate) {
        Accounts accounts = agent.getAccounts();
        Double nowAmount = accounts.getAccount(accountsType);
        if (amount != 0) {//不为零的时候才通知
            nowAmount = deductAccount(accountsType, accounts, amount, validate);
        }
        AccountsRecord record = new AccountsRecord(agent, casedAgent, accountsType, more, amount, nowAmount, new Date(), AccountsRecord.SUB);
        if (amount == 0) {
            record.setInfo(record.getInfo().replace("追回", "通知"));
        }
        return record;
    }

    /**
     * 增加账户
     * 生成记录
     *
     * @param
     * @param amount
     */
    public AccountsRecord increaseAccountAndRecord(AccountsType accountsType, Agent agent, Agent casedAgent, Double amount, String more) {
        Accounts accounts = agent.getAccounts();
        Double nowAmount = accounts.getAccount(accountsType);
        if (amount != 0) {//不为零的时候才通知
            nowAmount = increaseAccount(accountsType, accounts, amount);
        }
        AccountsRecord record = new AccountsRecord(agent, casedAgent, accountsType, more, amount, nowAmount, new Date(), AccountsRecord.ADD);
        if (amount == 0) {
            record.setInfo(record.getInfo().replace("利润", "通知"));
        }
        return record;
    }


    /**
     * 提高账户
     *
     * @param accounts
     * @param amount
     */
    private Double increaseAccount(AccountsType accountsType, Accounts accounts, Double amount) {
        validateAmount(amount);
        Double balance = accounts.getAccount(accountsType);//获取当前要转换的库存
        balance = PreciseComputeUtil.add(balance, amount);//加法计算
        accounts.setAccount(balance, accountsType);//设置为新的值
        return balance;
    }


    /**
     * 减少账户
     *
     * @param accounts
     * @param amount
     */
    private Double deductAccount(AccountsType accountsType, Accounts accounts, Double amount) {
//        validateAmount(amount);
//        Double balance = accounts.getAccount(accountsType);//获取当前要转换的库存
//        balance = PreciseComputeUtil.sub(balance, amount);//计算
//        validateResult(balance, accountsType);//验证结果
//        accounts.setAccount(balance, accountsType);//设置为新的值
        return deductAccount(accountsType, accounts, amount, true);
    }

    /**
     * 减少账户
     *
     * @param accounts
     * @param amount
     */
    private Double deductAccount(AccountsType accountsType, Accounts accounts, Double amount, boolean validate) {
        //四舍五入 保留两位小数
        validateAmount(amount);
        Double balance = accounts.getAccount(accountsType);//获取当前要转换的库存
        balance = PreciseComputeUtil.sub(balance, amount);//计算
        if (validate) {
            validateResult(balance, accountsType);//验证结果
        }
        accounts.setAccount(balance, accountsType);//设置为新的值
        return balance;
    }


    /**
     * 验证金额
     *
     * @param amount
     */
    private void validateAmount(Double amount) {
        if (amount <= 0 || !PreciseComputeUtil.isMoneyAmount(amount)) {//值非法
            throw new ApplicationException("金额输入错误！" + amount);
        }
    }


    /**
     * 验证结果
     *
     * @param result
     * @param accountsType
     * @return
     */
    private void validateResult(Double result, AccountsType accountsType) {
        if (result < 0) {
            throw new ApplicationException(accountsType.getStateInfo() + "余额不足");
        }
    }


    /**
     * 返回可用的代金券
     *
     * @param agent
     * @param amount
     * @return
     */
    public Double getAvailableVoucher(Agent agent, Double amount) {
        Double voucher = agent.getAccounts().getAccount(AccountsType.VOUCHER);
        if (voucher >= amount) {
            return amount;
        } else {
            throw new ApplicationException("代金券余额不足,需要" + amount);
        }
    }

    /**
     * 返回可用的进货券
     *
     * @param agent
     * @param amount
     * @return
     */
    public Double getAvailablePurchase(Agent agent, Double amount) {
        Double purchase = agent.getAccounts().getAccount(AccountsType.PURCHASE);
        amount = PreciseComputeUtil.round(amount * 0.03);//进货使用3%
        if (purchase >= amount) {
            return amount;
        } else {
            return purchase;//全用了
        }
    }


    @Override
    public Map<Agent, Double> rewardVoucher(List<Agent> parents, String voucherStr, Integer qunantity) {
        HashMap<Agent, Double> maps = new HashMap<>();
        //获得奖励参数
        Double[] vs = RewardUtil.getVsFromStr(voucherStr);
        //装载特殊获得奖励级别对应的获得奖励
        String[] tvipNames = new String[AgentLevelName.values().length - 1];
        for (int i = 0; i < AgentLevelName.values().length - 1; i++) {
            tvipNames[i] = AgentLevelName.values()[i].toString();
        }
        Map<String, Double> mapV = new HashMap<>();
        for (int i = 0; i < tvipNames.length; i++) {
            mapV.put(tvipNames[i], vs[i]);//特别vip的获得奖励
        }
        //截流总数
        Double sumReward = 0.0;
        //崔秀娟 特殊处理
        Boolean hasFenGs = false;
        //循环获得奖励
        for (int i = 0; i < parents.size(); i++) {
            Double result = 0.0;//该返的奖金
            String levelName = goodsAccountHandler.getMainGoodsAccount(parents.get(i)).getAgentLevel().getName();
            //如果是特殊vip
            if (mapV.containsKey(levelName)) {
                //增加获得奖励
                Double tem = PreciseComputeUtil.round(mapV.get(levelName) * qunantity);
                result = tem - sumReward;
                if (result < 0) {//减去已经返了的利润
                    result = 0.0;
                }
                sumReward += result;//累积已经返了的利
                //如果是静止或者苏雨薇
                if (parents.get(i).getAgentCode().equals("zmz934976") || parents.get(i).getAgentCode().equals("zmz015928")) {
                    //获取联盟单位与分公司的值的差价
                    Double cf = mapV.get(AgentLevelName.联盟单位.toString()) - mapV.get(AgentLevelName.分公司.toString());
                    result = result - cf * qunantity / 2;
                }
            }
            //加上基础的获得奖励
            result += RewardUtil.getVipVoucher(vs, i, qunantity);
            //如果获得奖励为0的大区不加入  其他级别也加入
            if (result.equals(0.0) && levelName.equals(AgentLevelName.大区.toString())) {
                continue;
            }
            //加入获得奖励map
            if (maps.containsKey(parents.get(i))) {
                Double temp = maps.get(parents.get(i));
                maps.put(parents.get(i), PreciseComputeUtil.add(temp, result));
            } else {
                maps.put(parents.get(i), result);
            }
        }
        return maps;
    }


    @Override
    public Map<Agent, Double> rewardPmallVoucher(List<Agent> parents, Integer qunantity, Double profit) {
        HashMap<Agent, Double> maps = new HashMap<>();
//        Map<String, Double> mapV = new HashMap<>();
        //截流总数
        Double sumReward = 0.0;
        //崔秀娟 特殊处理
        Boolean hasFenGs = false;
        //循环获得奖励
        for (int i = 0; i < parents.size(); i++) {
            Double result;//该返的奖金
            String levelName = agentHandler.getLevelName(parents.get(i));
            //增加获得奖励
            Double tem = getVipPerCent(parents.get(i)) * profit * qunantity;//获取额外的获得奖励
            result = tem - sumReward;
            if (result < 0) {//减去已经返了的利润
                result = 0.0;
            }
            sumReward += result;//累积已经返了的利
            //如果是崔秀娟 且有如果有分公司
            if (levelName.contains(AgentLevelName.分公司.toString())) {
                hasFenGs = true;
            }
            if (parents.get(i).getAgentCode() != null && parents.get(i).getAgentCode().equals("zmz126786") && hasFenGs) {
                result = result / 2;
            }

            if (i < basePercent.length) {
                //加上基础的获得奖励
                result += basePercent[i] * profit * qunantity;//获得奖励比*毛利润*数量
            }

            result = PreciseComputeUtil.round(result);

            //如果获得奖励为0不加入
            if (result.equals(0.0)) {
                continue;
            }
            //加入获得奖励map
            if (maps.containsKey(parents.get(i))) {
                Double temp = maps.get(parents.get(i));
                maps.put(parents.get(i), PreciseComputeUtil.add(temp, result));
            } else {
                maps.put(parents.get(i), result);
            }
        }
        return maps;
    }

    public Map<Agent, Double> rewardPmallVoucher(Agent agent, PmallGoods goods, Integer qunantity) {
        Map<Agent, Double> map = new HashedMap();
        Double[] vs = RewardUtil.getVsFromStr(goods.getVouchers());
        for (int i = 0; i < vs.length; i++) {
            Agent parent = agent.getParent();
            if(parent==null||parent.isMutedUser()){
                break;
            }
            Double tem = PreciseComputeUtil.mul(vs[i],qunantity);
            if(tem>0){
                map.put(parent,tem);
            }
            agent = agent.getParent();
        }
        return map;
    }










    /**
     * 转货返利
     * @param fromAgent    --发货人
     * @param toAgent      --收货人
     * @param goods        --商品
     * @param qunantity    --数量
     * @return
     */
    public List<AccountsTransfer> rewardhjgnVoucher(Agent fromAgent, Agent toAgent, Goods goods, Integer qunantity) {

        //todo list用来保存进货返利的利润信息
        List<AccountsTransfer> list = new ArrayList<>();

        //todo 收货人ID
        Integer toId = toAgent.getId();

        //todo 收货人上级ID
        Integer toParentId = toAgent.getParent().getId();

        //todo 发货人ID
        Integer fromId = fromAgent.getId();

        //todo 发货人的等级
        AgentLevel fromLevel = agentHandler.getLevel(fromAgent);

        //todo 发货人的拿货价格
        Price from = priceHandler.getPrice(fromAgent,goods);
        Double fromPrice = from.getPrice();

        //todo 收货人的等级        -- 没有升级时
        AgentLevel toLevel = agentHandler.getLevel(toAgent);

        //todo 收货人的拿货单价     -- 没有升级时
        Price to = priceHandler.getPrice(toAgent,goods);
        Double toPrice = to.getPrice();

        //todo 收货人的进货标准量
        Integer threshold = to.getThreshold();

        //todo 是否满足进货标准
        if(qunantity >= threshold){

            //todo 升级时

            //todo 接收新等级
            AgentLevel newLevel;

            //todo new一个新的收货人
            Agent newToAgent = new Agent();

            //todo 获取Price
            List<Price> listPrice = priceHandler.findPrice();

            for(int i = 0; i< listPrice.size(); i++){
                Price price = listPrice.get(i);
                //todo 判断这次升级到什么位置
                if(price.getThreshold() <= qunantity && qunantity < price.getThresholdSection()){

                    //todo 新的等级赋值
                    newLevel = price.getAgentLevel();

                    //todo 如果新的和旧的相等，就表示没有升级   17
                    if(newLevel.getLevel() == toLevel.getLevel()){

                        if(fromLevel.getLevel() <= toLevel.getLevel()){

                            //todo 本次转货的信息  -- 没有升级时
                            Double amount = PreciseComputeUtil.mul(toPrice,qunantity);
                            String remark = toAgent.getRealName()+"向"+fromAgent.getRealName()+"进货"+qunantity+"盒，总金额："+amount+"元";
                            AccountsTransfer accountsTransfer = transferProfit(fromAgent,toAgent,new Date(),new Date(),remark,amount,AccountsTransferStatus.TRANSFER,true);
                            list.add(accountsTransfer);

                            // todo 没有升级时

                            // todo 如果收货人是由发货人推荐的，并且等级低于发货人，利润全部给发货人   -- 管理员也一样
                            if((toId != fromId && fromId == toParentId && toLevel.getLevel() > fromLevel.getLevel())
                                    || (fromAgent.getAgentCode().equals("01") && toId != fromId && toLevel.getLevel() > fromLevel.getLevel())) {
                                //todo 判断发货人是不是管理员
                                if(fromAgent.getAgentCode().equals("01")){
                                    Double profit1 = 0.0;
                                    String remark2 = toAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + fromAgent.getRealName() + "-管理员出货不需要差价返利利润,直接按当前代理等级的进货价格给他即可";
                                    AccountsTransfer transferProfit10 = transferProfit(fromAgent,toAgent,new Date(),new Date(),remark2,profit1,AccountsTransferStatus.TRANSFER,true);
                                    list.add(transferProfit10);
                                }else {
                                    Double profit = (toPrice - fromPrice) * qunantity;
                                    String remark1 = toAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + fromAgent.getRealName() + "获得差价返利：" + profit + "元";
                                    AccountsTransfer transferProfits = transferProfit(fromAgent, toAgent, new Date(), new Date(), remark1, profit, AccountsTransferStatus.TRANSFER, true);
                                    list.add(transferProfits);
                                }

                                //todo 如果收货人的等级是省级，那就累计他的进货总金额
                                if (toLevel.getLevel() == 5) {
                                    Double totalAmount = toAgent.getTotalAmount() + toPrice * qunantity;
                                    toAgent.setTotalAmount(totalAmount);
                                    agentHandler.merge(toAgent);

                                    //todo 省级平级利润
                                    List<AccountsTransfer> accountsTransferList = LevelingProfit(fromAgent,newToAgent,qunantity);
                                    if(accountsTransferList.size() > 0){
                                        for(int j = 0; j < accountsTransferList.size(); j++){
                                            AccountsTransfer accountsTransfer1 = accountsTransferList.get(j);
                                            list.add(accountsTransfer1);
                                        }
                                    }
                                }

                                //todo 区域服务利润
                                AccountsTransfer transferProfits1 = findAgentByAddress(fromAgent, toAgent, qunantity);
                                if (transferProfits1.getFromAgent() != null && transferProfits1.getToAgent() != null) {
                                    list.add(transferProfits1);
                                }
                            }
                        }else{
                            throw new ApplicationException("(不升级时)请找上级给你转货!平级下级无法完成转货!");
                        }
                    }else{

                        //todo 对代理进行升级
                        newToAgent = toAgent;

                        //todo 大区 分公司 联盟单位 暂时不自动升级
//                        if(newLevel.getLevel() == 5
//                                || newLevel.getLevel() == 6 && newToAgent.getTotalAmount() > 500000
//                                || newLevel.getLevel() == 7 && newToAgent.getTotalAmount() > 1000000
//                                || newLevel.getLevel() == 8 && newToAgent.getTotalAmount() > 2000000){

                        if(newLevel.getLevel() >= 5){
                            GoodsAccount newGoodsAccount = new GoodsAccount();
                            for (GoodsAccount goodsAccount : toAgent.getGoodsAccounts()) {
                                newGoodsAccount.setGoods(goodsAccount.getGoods());
                                newGoodsAccount.setId(goodsAccount.getId());
                                newGoodsAccount.setCurrentBalance(goodsAccount.getCurrentBalance());
                                newGoodsAccount.setUser(goodsAccount.getUser());
                                newGoodsAccount.setCumulative(goodsAccount.getCumulative());
                                newGoodsAccount.setCurrentPoint(goodsAccount.getCurrentPoint());
                                newGoodsAccount.setUpdateTime(goodsAccount.getUpdateTime());
                                newGoodsAccount.setVersion(goodsAccount.getVersion());
                                newGoodsAccount.setCurrentBalance(goodsAccount.getCurrentBalance());
                                newGoodsAccount.setAgentLevel(newLevel);
                            }
                            Set<GoodsAccount> goodsAccountSet = new HashSet<>();
                            goodsAccountSet.add(newGoodsAccount);
                            newToAgent.setGoodsAccounts(goodsAccountSet);
                            //todo 修改等级
                            newToAgent = agentHandler.merge(newToAgent);

                            //todo 收货人的等级       -- 升级后
                            AgentLevel newToLevel = agentHandler.getLevel(newToAgent);

                            //todo 收货人的拿货单价    -- 升级后
                            Price newTo = priceHandler.getPrice(newToAgent,goods);
                            Double newToPrice = newTo.getPrice();

                            //todo 收货人上级等级     -- 没有升级时
                            Agent toParentAgent = agentHandler.get(toParentId);
                            AgentLevel toLevelParent = agentHandler.getLevel(toParentAgent);

                            if(fromLevel.getLevel() <= newToLevel.getLevel()){

                                //todo 本次转货的信息  -- 升级后
                                Double amount = PreciseComputeUtil.mul(newToPrice,qunantity);
                                String remark = newToAgent.getRealName()+"向"+fromAgent.getRealName()+"进货"+qunantity+"盒，总金额："+amount+"元，并且"+newToAgent.getRealName()+"由"+toLevel.getName()+"升级为："+newToAgent.getLevelName();
                                AccountsTransfer accountsTransfer = transferProfit(fromAgent,newToAgent,new Date(),new Date(),remark,amount,AccountsTransferStatus.TRANSFER,true);
                                list.add(accountsTransfer);

                                //todo 如果收货人升级和推荐人同级时， 利润平分由当前发货人和推荐人平分    -- 管理员也一样
                                if((fromLevel.getLevel() < newToLevel.getLevel() && toLevelParent.getLevel() == newToLevel.getLevel())
                                        || (fromAgent.getAgentCode().equals("01") && fromLevel.getLevel() < newToLevel.getLevel() && toLevelParent.getLevel() == newToLevel.getLevel())){
                                    //todo 如果收货人的等级是省级，那就累计他的进货总金额
                                    if(newToLevel.getLevel() == 5){
                                        Double original = Double.valueOf(newToAgent.getTotalAmount());
                                        Double thisTime = newToPrice * qunantity;
                                        Double totalAmount =  original + thisTime;
                                        toAgent.setTotalAmount(totalAmount);
                                        agentHandler.merge(toAgent);

                                        //todo 省级平级利润
                                        List<AccountsTransfer> accountsTransferList = LevelingProfit(fromAgent,newToAgent,qunantity);
                                        if(accountsTransferList != null){
                                            for(int j = 0; j < accountsTransferList.size(); j++){
                                                AccountsTransfer accountsTransfer1 = accountsTransferList.get(j);
                                                list.add(accountsTransfer1);
                                            }
                                        }
                                    }
                                    //todo 判断发货人是不是管理员
                                    if(fromAgent.getAgentCode().equals("01")){
                                        Double profit1 = 0.0;
                                        String remark2 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + fromAgent.getRealName() + "-管理员出货不需要差价返利利润,直接按当前代理等级的进货价格给他即可";
                                        AccountsTransfer transferProfit10 = transferProfit(fromAgent,newToAgent,new Date(),new Date(),remark2,profit1,AccountsTransferStatus.TRANSFER,true);
                                        list.add(transferProfit10);
                                        Double profit2 = (newToPrice - fromPrice) * qunantity * 0.5;
                                        String remark3 = newToAgent.getRealName()+"向"+fromAgent.getRealName()+"进货"+qunantity+"盒，"+toParentAgent.getRealName()+"获得推荐返利："+profit2+"元";
                                        AccountsTransfer transferProfit2 = transferProfit(fromAgent,newToAgent,new Date(),new Date(),remark3,profit2,AccountsTransferStatus.TRANSFER,true);
                                        list.add(transferProfit2);
                                    }else{
                                        Double profit1 = (newToPrice - fromPrice) * qunantity * 0.5;
                                        Double profit2 = (newToPrice - fromPrice) * qunantity * 0.5;
                                        String remark2 = newToAgent.getRealName()+"向"+fromAgent.getRealName()+"进货"+qunantity+"盒，"+fromAgent.getRealName()+"获得差价返利："+profit1+"元";
                                        AccountsTransfer transferProfit1 = transferProfit(fromAgent,newToAgent,new Date(),new Date(),remark2,profit1,AccountsTransferStatus.TRANSFER,true);
                                        list.add(transferProfit1);
                                        String remark3 = newToAgent.getRealName()+"向"+fromAgent.getRealName()+"进货"+qunantity+"盒，"+toParentAgent.getRealName()+"获得推荐返利："+profit2+"元";
                                        AccountsTransfer transferProfit2 = transferProfit(fromAgent,newToAgent,new Date(),new Date(),remark3,profit2,AccountsTransferStatus.TRANSFER,true);
                                        list.add(transferProfit2);
                                    }

                                    //todo 区域服务利润
                                    AccountsTransfer transferProfits1 = findAgentByAddress(fromAgent,toAgent,qunantity);
                                    if (transferProfits1.getFromAgent() != null && transferProfits1.getToAgent() != null) {
                                        list.add(transferProfits1);
                                    }

                                }else if((fromLevel.getLevel() < newToLevel.getLevel() && toLevelParent.getLevel() < newToLevel.getLevel() && newToLevel.getLevel() < toLevel.getLevel())
                                         || (fromAgent.getAgentCode().equals("01") && fromLevel.getLevel() < newToLevel.getLevel() && toLevelParent.getLevel() < newToLevel.getLevel() && newToLevel.getLevel() < toLevel.getLevel())){

                                    //todo 如果收货人的等级是省级，那就累计他的进货总金额
                                    if(newToLevel.getLevel() == 5){
                                        Double original = Double.valueOf(newToAgent.getTotalAmount());
                                        Double thisTime = newToPrice * qunantity;
                                        Double totalAmount =  original + thisTime;
                                        toAgent.setTotalAmount(totalAmount);
                                        agentHandler.merge(toAgent);

                                        //todo 省级平级利润
                                        List<AccountsTransfer> accountsTransferList = LevelingProfit(fromAgent,newToAgent,qunantity);
                                        if(accountsTransferList != null){
                                            for(int j = 0; j < accountsTransferList.size(); j++){
                                                AccountsTransfer accountsTransfer1 = accountsTransferList.get(j);
                                                list.add(accountsTransfer1);
                                            }
                                        }
                                    }
                                    //todo 判断发货人是不是管理员
                                    if(fromAgent.getAgentCode().equals("01")){
                                        Double profit1 = 0.0;
                                        String remark2 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + fromAgent.getRealName() + "-管理员出货不需要差价返利利润,直接按当前代理等级的进货价格给他即可";
                                        AccountsTransfer transferProfit10 = transferProfit(fromAgent,newToAgent,new Date(),new Date(),remark2,profit1,AccountsTransferStatus.TRANSFER,true);
                                        list.add(transferProfit10);
//                                        Double profit2 = (newToPrice - fromPrice) * qunantity * 0.5;
//                                        String remark3 = newToAgent.getRealName()+"向"+fromAgent.getRealName()+"进货"+qunantity+"盒，"+toParentAgent.getRealName()+"获得推荐返利："+profit2+"元";
//                                        AccountsTransfer transferProfit2 = transferProfit(fromAgent,newToAgent,new Date(),new Date(),remark3,profit2,AccountsTransferStatus.TRANSFER,true);
//                                        list.add(transferProfit2);
                                    }else{
                                        Double profit1 = (newToPrice - fromPrice) * qunantity * 0.5;
                                        Double profit2 = (newToPrice - fromPrice) * qunantity * 0.5;
                                        String remark2 = newToAgent.getRealName()+"向"+fromAgent.getRealName()+"进货"+qunantity+"盒，"+fromAgent.getRealName()+"获得差价返利："+profit1+"元";
                                        AccountsTransfer transferProfit1 = transferProfit(fromAgent,newToAgent,new Date(),new Date(),remark2,profit1,AccountsTransferStatus.TRANSFER,true);
                                        list.add(transferProfit1);
                                        String remark3 = newToAgent.getRealName()+"向"+fromAgent.getRealName()+"进货"+qunantity+"盒，"+toParentAgent.getRealName()+"获得推荐返利："+profit2+"元";
                                        AccountsTransfer transferProfit2 = transferProfit(fromAgent,newToAgent,new Date(),new Date(),remark3,profit2,AccountsTransferStatus.TRANSFER,true);
                                        list.add(transferProfit2);
                                    }

                                    //todo 区域服务利润
                                    AccountsTransfer transferProfits1 = findAgentByAddress(fromAgent,toAgent,qunantity);
                                    if (transferProfits1.getFromAgent() != null && transferProfits1.getToAgent() != null) {
                                        list.add(transferProfits1);
                                    }

                                }else{
                                    String levelName = newToLevel.getName();
                                    //todo 县
                                    boolean county = levelName.contains("县");
                                    if(county){
                                        //todo 判断发货人是不是管理员
                                        if(fromAgent.getAgentCode().equals("01")){
                                            Double profit1 = 0.0;
                                            String remark2 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + fromAgent.getRealName() + "-管理员出货不需要差价返利利润,直接按当前代理等级的进货价格给他即可";
                                            AccountsTransfer transferProfit10 = transferProfit(fromAgent,newToAgent,new Date(),new Date(),remark2,profit1,AccountsTransferStatus.TRANSFER,true);
                                            list.add(transferProfit10);
                                            Double profit2 = (newToPrice - fromPrice) * qunantity * 0.25;
                                            String remark3 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + toParentAgent.getRealName() + "获得推荐返利：" + profit2 + "元";
                                            AccountsTransfer transferProfit2 = transferProfit(fromAgent, newToAgent, new Date(), new Date(), remark3, profit2, AccountsTransferStatus.TRANSFER, true);
                                            list.add(transferProfit2);
                                        }else{
                                            Double profit1 = (newToPrice - fromPrice) * qunantity * 0.5;
                                            Double profit2 = (newToPrice - fromPrice) * qunantity * 0.25;
                                            String remark2 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + fromAgent.getRealName() + "获得差价返利：" + profit1 + "元";
                                            AccountsTransfer transferProfit1 = transferProfit(fromAgent, newToAgent, new Date(), new Date(), remark2, profit1, AccountsTransferStatus.TRANSFER, true);
                                            list.add(transferProfit1);
                                            String remark3 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + toParentAgent.getRealName() + "获得推荐返利：" + profit2 + "元";
                                            AccountsTransfer transferProfit2 = transferProfit(fromAgent, newToAgent, new Date(), new Date(), remark3, profit2, AccountsTransferStatus.TRANSFER, true);
                                            list.add(transferProfit2);
                                        }

                                        //todo 区域服务利润
                                        AccountsTransfer transferProfits1 = findAgentByAddress(fromAgent,toAgent,qunantity);
                                        if (transferProfits1.getFromAgent() != null && transferProfits1.getToAgent() != null) {
                                            list.add(transferProfits1);
                                        }
                                    }else{
                                        //todo 市
                                        boolean city = levelName.contains("市");
                                        if(city){
                                            //todo 判断发货人是不是管理员
                                            if(fromAgent.getAgentCode().equals("01")){
                                                Double profit1 = 0.0;
                                                String remark2 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + fromAgent.getRealName() + "-管理员出货不需要差价返利利润,直接按当前代理等级的进货价格给他即可";
                                                AccountsTransfer transferProfit10 = transferProfit(fromAgent,newToAgent,new Date(),new Date(),remark2,profit1,AccountsTransferStatus.TRANSFER,true);
                                                list.add(transferProfit10);
//                                                Double profit2 = (newToPrice - fromPrice) * qunantity * 0.125;
//                                                String remark3 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + toParentAgent.getRealName() + "获得推荐返利：" + profit2 + "元";
//                                                AccountsTransfer transferProfit2 = transferProfit(fromAgent, newToAgent, new Date(), new Date(), remark3, profit2, AccountsTransferStatus.TRANSFER, true);
//                                                list.add(transferProfit2);
                                            }else {
                                                Double profit1 = (newToPrice - fromPrice) * qunantity * 0.5;
                                                Double profit2 = (newToPrice - fromPrice) * qunantity * 0.125;
                                                String remark2 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + fromAgent.getRealName() + "获得差价返利：" + profit1 + "元";
                                                AccountsTransfer transferProfit1 = transferProfit(fromAgent, newToAgent, new Date(), new Date(), remark2, profit1, AccountsTransferStatus.TRANSFER, true);
                                                list.add(transferProfit1);
                                                String remark3 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + toParentAgent.getRealName() + "获得推荐返利：" + profit2 + "元";
                                                AccountsTransfer transferProfit2 = transferProfit(fromAgent, newToAgent, new Date(), new Date(), remark3, profit2, AccountsTransferStatus.TRANSFER, true);
                                                list.add(transferProfit2);
                                            }

                                            //todo 区域服务利润
                                            AccountsTransfer transferProfits1 = findAgentByAddress(fromAgent,toAgent,qunantity);
                                            if (transferProfits1.getFromAgent() != null && transferProfits1.getToAgent() != null) {
                                                list.add(transferProfits1);
                                            }
                                        }else{
                                            //todo 省  判断等级是否是省级
                                            boolean province = levelName.contains("省");
                                            if(province){
                                                //todo 判断发货人是不是管理员
                                                if(fromAgent.getAgentCode().equals("01")){
                                                    Double profit1 = 0.0;
                                                    String remark2 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + fromAgent.getRealName() + "-管理员出货不需要差价返利利润,直接按当前代理等级的进货价格给他即可";
                                                    AccountsTransfer transferProfit10 = transferProfit(fromAgent,newToAgent,new Date(),new Date(),remark2,profit1,AccountsTransferStatus.TRANSFER,true);
                                                    list.add(transferProfit10);
//                                                    Double profit2 = (newToPrice - fromPrice) * qunantity * 0.0625;
//                                                    String remark3 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + toParentAgent.getRealName() + "获得推荐返利：" + profit2 + "元";
//                                                    AccountsTransfer transferProfit2 = transferProfit(fromAgent, newToAgent, new Date(), new Date(), remark3, profit2, AccountsTransferStatus.TRANSFER, true);
//                                                    list.add(transferProfit2);
                                                }else {
                                                    Double profit1 = (newToPrice - fromPrice) * qunantity * 0.5;
                                                    Double profit2 = (newToPrice - fromPrice) * qunantity * 0.0625;
                                                    String remark2 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒," + fromAgent.getRealName() + "获得差价返利：" + profit1 + "元";
                                                    AccountsTransfer transferProfit1 = transferProfit(fromAgent, newToAgent, new Date(), new Date(), remark2, profit1, AccountsTransferStatus.TRANSFER, true);
                                                    list.add(transferProfit1);
                                                    String remark3 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + toParentAgent.getRealName() + "获得推荐返利：" + profit2 + "元";
                                                    AccountsTransfer transferProfit2 = transferProfit(fromAgent, newToAgent, new Date(), new Date(), remark3, profit2, AccountsTransferStatus.TRANSFER, true);
                                                    list.add(transferProfit2);
                                                }

                                                //todo 区域服务利润
                                                AccountsTransfer transferProfits1 = findAgentByAddress(fromAgent,toAgent,qunantity);
                                                if (transferProfits1.getFromAgent() != null && transferProfits1.getToAgent() != null) {
                                                    list.add(transferProfits1);
                                                }

                                                //todo 如果收货人的等级是省级，那就累计他的进货总金额(清零累计的)
                                                if(newToLevel.getLevel() == 5){
                                                    Double totalAmount = newToAgent.getTotalAmount() + newToPrice * qunantity;
                                                    newToAgent.setTotalAmount(totalAmount);
                                                    agentHandler.merge(newToAgent);

                                                    //todo 省级平级利润
                                                    List<AccountsTransfer> accountsList = LevelingProfit(fromAgent,newToAgent,qunantity);
                                                    if(accountsList != null){
                                                        //todo 有几个赋值几个吧 没有就算了
                                                        for(int k = 0; k < accountsList.size(); k++){
                                                            AccountsTransfer accountsTransfer2 = accountsList.get(k);
                                                            list.add(accountsTransfer2);
                                                        }
                                                    }
                                                }

                                            }else{
                                                //todo 大区  判断等级是否是省级并且进货金额超过50万
                                                boolean DaQu = levelName.contains("大区");
                                                if(DaQu){
                                                    if(newToAgent.getTotalAmount() >= 500000){
                                                        //todo 判断发货人是不是管理员
                                                        if(fromAgent.getAgentCode().equals("01")){
                                                            Double profit1 = 0.0;
                                                            String remark2 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + fromAgent.getRealName() + "-管理员出货不需要差价返利利润,直接按当前代理等级的进货价格给他即可";
                                                            AccountsTransfer transferProfit10 = transferProfit(fromAgent,newToAgent,new Date(),new Date(),remark2,profit1,AccountsTransferStatus.TRANSFER,true);
                                                            list.add(transferProfit10);
                                                            //todo 10
//                                                            Double profit2 = (fromPrice - newToPrice) * qunantity * 0.03125;
//                                                            String remark3 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + toParentAgent.getRealName() + "获得推荐返利：" + profit2 + "元";
//                                                            AccountsTransfer transferProfit2 = transferProfit(fromAgent, newToAgent, new Date(), new Date(), remark3, profit2, AccountsTransferStatus.TRANSFER, true);
//                                                            list.add(transferProfit2);
                                                        }else {
                                                            Double profit1 = (fromPrice - newToPrice) * qunantity * 0.5;
                                                            Double profit2 = (fromPrice - newToPrice) * qunantity * 0.03125;
                                                            String remark2 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + fromAgent.getRealName() + "获得差价返利：" + profit1 + "元";
                                                            AccountsTransfer transferProfit1 = transferProfit(fromAgent, newToAgent, new Date(), new Date(), remark2, profit1, AccountsTransferStatus.TRANSFER, true);
                                                            list.add(transferProfit1);
                                                            String remark3 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + toParentAgent.getRealName() + "获得推荐返利：" + profit2 + "元";
                                                            AccountsTransfer transferProfit2 = transferProfit(fromAgent, newToAgent, new Date(), new Date(), remark3, profit2, AccountsTransferStatus.TRANSFER, true);
                                                            list.add(transferProfit2);
                                                        }
                                                        //todo 区域服务利润
                                                        AccountsTransfer transferProfits1 = findAgentByAddress(fromAgent,toAgent,qunantity);
                                                        if (transferProfits1.getFromAgent() != null && transferProfits1.getToAgent() != null) {
                                                            list.add(transferProfits1);
                                                        }
                                                    }else{
                                                        throw new ApplicationException("升级为大区的规则：等级达到省级后再开始累计进货的总金额并且超过50万元才能升级为大区!");
                                                    }
                                                }else{
                                                    //todo 分公司  判断等级是否是省级并且进货金额超过100万
                                                    boolean Fen = levelName.contains("分公司");
                                                    if(Fen){
                                                        if(newToAgent.getTotalAmount() >= 1000000){
                                                            //todo 判断发货人是不是管理员
                                                            if(fromAgent.getAgentCode().equals("01")){
                                                                Double profit1 = 0.0;
                                                                String remark2 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + fromAgent.getRealName() + "-管理员出货不需要差价返利利润,直接按当前代理等级的进货价格给他即可";
                                                                AccountsTransfer transferProfit10 = transferProfit(fromAgent,newToAgent,new Date(),new Date(),remark2,profit1,AccountsTransferStatus.TRANSFER,true);
                                                                list.add(transferProfit10);
                                                                //todo 20
//                                                                Double profit2 = (fromPrice - newToPrice) * qunantity * 0.015625;
//                                                                String remark3 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + toParentAgent.getRealName() + "获得推荐返利：" + profit2 + "元";
//                                                                AccountsTransfer transferProfit2 = transferProfit(fromAgent, newToAgent, new Date(), new Date(), remark3, profit2, AccountsTransferStatus.TRANSFER, true);
//                                                                list.add(transferProfit2);
                                                            }else {
                                                                Double profit1 = (fromPrice - newToPrice) * qunantity * 0.5;
                                                                Double profit2 = (fromPrice - newToPrice) * qunantity * 0.015625;
                                                                String remark2 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + fromAgent.getRealName() + "获得差价返利：" + profit1 + "元";
                                                                AccountsTransfer transferProfit1 = transferProfit(fromAgent, newToAgent, new Date(), new Date(), remark2, profit1, AccountsTransferStatus.TRANSFER, true);
                                                                list.add(transferProfit1);
                                                                String remark3 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + toParentAgent.getRealName() + "获得推荐返利：" + profit2 + "元";
                                                                AccountsTransfer transferProfit2 = transferProfit(fromAgent, newToAgent, new Date(), new Date(), remark3, profit2, AccountsTransferStatus.TRANSFER, true);
                                                                list.add(transferProfit2);
                                                            }
                                                            //todo 区域服务利润
                                                            AccountsTransfer transferProfits1 = findAgentByAddress(fromAgent,toAgent,qunantity);
                                                            if (transferProfits1.getFromAgent() != null && transferProfits1.getToAgent() != null) {
                                                                list.add(transferProfits1);
                                                            }
                                                        }else{
                                                            throw new ApplicationException("升级为分公司的规则：等级达到省级后再开始累计进货的总金额并且超过100万元才能升级为分公司!");
                                                        }
                                                    }else{
                                                        //todo 联盟单位  判断等级是否是省级并且进货金额超过200万
                                                        boolean LianMeng = levelName.contains("联盟");
                                                        if(LianMeng){
                                                            if(newToAgent.getTotalAmount() >= 2000000){
                                                                //todo 判断发货人是不是管理员
                                                                if(fromAgent.getAgentCode().equals("01")){
                                                                    Double profit1 = 0.0;
                                                                    String remark2 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + fromAgent.getRealName() + "-管理员出货不需要差价返利利润,直接按当前代理等级的进货价格给他即可";
                                                                    AccountsTransfer transferProfit10 = transferProfit(fromAgent,newToAgent,new Date(),new Date(),remark2,profit1,AccountsTransferStatus.TRANSFER,true);
                                                                    list.add(transferProfit10);
                                                                    //todo 30
//                                                                    Double profit2 = (fromPrice - newToPrice) * qunantity * 0.0078125;
//                                                                    String remark3 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + toParentAgent.getRealName() + "获得推荐返利：" + profit2 + "元";
//                                                                    AccountsTransfer transferProfit2 = transferProfit(fromAgent, newToAgent, new Date(), new Date(), remark3, profit2, AccountsTransferStatus.TRANSFER, true);
//                                                                    list.add(transferProfit2);
                                                                }else {
                                                                    Double profit1 = (fromPrice - newToPrice) * qunantity * 0.5;
                                                                    Double profit2 = (fromPrice - newToPrice) * qunantity * 0.0078125;
                                                                    String remark2 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + fromAgent.getRealName() + "获得差价返利：" + profit1 + "元";
                                                                    AccountsTransfer transferProfit1 = transferProfit(fromAgent, newToAgent, new Date(), new Date(), remark2, profit1, AccountsTransferStatus.TRANSFER, true);
                                                                    list.add(transferProfit1);
                                                                    String remark3 = newToAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + toParentAgent.getRealName() + "获得推荐返利：" + profit2 + "元";
                                                                    AccountsTransfer transferProfit2 = transferProfit(fromAgent, newToAgent, new Date(), new Date(), remark3, profit2, AccountsTransferStatus.TRANSFER, true);
                                                                    list.add(transferProfit2);
                                                                }
                                                                //todo 区域服务利润
                                                                AccountsTransfer transferProfits1 = findAgentByAddress(fromAgent,toAgent,qunantity);
                                                                if (transferProfits1.getFromAgent() != null && transferProfits1.getToAgent() != null) {
                                                                    list.add(transferProfits1);
                                                                }
                                                            }else{
                                                                throw new ApplicationException("升级为联盟单位的规则：等级达到省级后再开始累计进货的总金额并且超过200万元才能升级为联盟单位!");
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }else{
                                throw new ApplicationException("(升级时)请找上级给你转货!平级下级无法完成转货!");
                            }
                        }
                    }
                }
            }
        }else{
            throw new ApplicationException("没有达到"+toLevel.getName()+"代理商的拿货标准数量!");
        }
        return list;
    }

    /**
     * 封装转货账单记录
     * @param fromAgent
     * @param toAgent
     * @param transferTime
     * @param updateTime
     * @param remark
     * @param amount
     * @param status
     * @param canShow
     * @return
     */
    public AccountsTransfer transferProfit(Agent fromAgent, Agent toAgent,Date transferTime,Date updateTime,String remark,Double amount,AccountsTransferStatus status,Boolean canShow){
        AccountsTransfer accountsTransfer = new AccountsTransfer();
        accountsTransfer.setFromAgent(fromAgent);
        accountsTransfer.setToAgent(toAgent);
        accountsTransfer.setTransferTime(transferTime);
        accountsTransfer.setStatus(status);
        accountsTransfer.setCanShow(canShow);
        accountsTransfer.setAmount(amount);
        accountsTransfer.setRemark(remark);
        accountsTransfer.setUpdateTime(updateTime);
        return accountsTransfer;
    }

    /**
     * 封装区域
     * @param fromAgent
     * @param toAgent
     * @param qunantity
     * @return
     */
    public AccountsTransfer findAgentByAddress(Agent fromAgent,Agent toAgent,Integer qunantity){

        AccountsTransfer transferProfits = new AccountsTransfer();

        String province = toAgent.getProvince();
        String city = toAgent.getCity();
        String county = toAgent.getCounty();

        List listAddress = agentHandler.findAgentByAddress(province,city,county);

        List listProvince = agentHandler.findAgentByProvince(province);

        List listCity = agentHandler.findAgentByProvinceAndCity(province,city);

        if(!listAddress.isEmpty() && listAddress != null){
            if(listAddress.size() > 1){
                throw new ApplicationException("区域服务利润中地址信息不对!存在多人享受县级区域利润");
            }else{
                User user = (User) listAddress.get(0);
                Agent agentAddress = agentHandler.get(user.getId());
                AgentLevel addressLevel = agentHandler.getLevel(agentAddress);
                String name = addressLevel.getName();
                //todo 县级服务利润  满足省级
                if(user.getRegionProfitProvince().equals(province) && user.getRegionProfitCity().equals(city) && user.getRegionProfitCounty().equals(county)){
                    //包含省且等于5
                    boolean status = name.contains("省");
                    if (status) {
                        if (addressLevel.getLevel() == 5) {
                            Double regionProfit = Double.valueOf(qunantity * 10);
                            String remark2 = toAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + agentAddress.getRealName() + "获得县级区域服务利润：" + regionProfit + "元";
                            transferProfits = transferProfit(fromAgent, toAgent, new Date(), new Date(), remark2, regionProfit, AccountsTransferStatus.TRANSFER, true);
                        }
                    }
                }
            }
        }else{
            if(!listCity.isEmpty() && listCity != null){
                if(listCity.size() > 1){
                    throw new ApplicationException("区域服务利润中地址信息不对!存在多人享受市级区域利润");
                }else {
                    User userCity = (User) listCity.get(0);
                    Agent agentCity = agentHandler.get(userCity.getId());
                    AgentLevel cityLevel = agentHandler.getLevel(agentCity);
                    String cityName = cityLevel.getName();
                    //todo 市级服务利润  满足省级和满足35万
                    if (userCity.getRegionProfitProvince().equals(province) && userCity.getRegionProfitCity().equals(city) && "".equals(userCity.getRegionProfitCounty())) {
                        if(userCity.getTotalAmount() > 350000) {
                            //包含省且等于5
                            boolean status = cityName.contains("省");
                            if (status) {
                                if (cityLevel.getLevel() == 5) {
                                    Double regionProfit = Double.valueOf(qunantity * 3);
                                    String remark2 = toAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + agentCity.getRealName() + "获得市级区域服务利润：" + regionProfit + "元";
                                    transferProfits = transferProfit(fromAgent, toAgent, new Date(), new Date(), remark2, regionProfit, AccountsTransferStatus.TRANSFER, true);
                                }
                            }
                        }
                    }
                }
            } else{
                if(!listProvince.isEmpty() && listProvince != null){
                    if(listProvince.size() > 1){
                        throw new ApplicationException("区域服务利润中地址信息不对!存在多人享受省级区域利润");
                    }else {
                        User userProvince = (User) listProvince.get(0);
                        Agent agentProvince = agentHandler.get(userProvince.getId());
                        AgentLevel provinceLevel = agentHandler.getLevel(agentProvince);
                        String provinceName = provinceLevel.getName();
                        //todo 省级服务利润  满足省级和满足70万
                        if (userProvince.getRegionProfitProvince().equals(province) && "".equals(userProvince.getRegionProfitCity()) && "".equals(userProvince.getRegionProfitCounty())) {
                            if(userProvince.getTotalAmount() > 700000){
                                //包含省且等于5
                                boolean status = provinceName.contains("省");
                                if (status) {
                                    if (provinceLevel.getLevel() == 5) {
                                        Double regionProfit = Double.valueOf(qunantity * 5);
                                        String remark2 = toAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + agentProvince.getRealName() + "获得省级区域服务利润：" + regionProfit + "元";
                                        transferProfits = transferProfit(fromAgent, toAgent, new Date(), new Date(), remark2, regionProfit, AccountsTransferStatus.TRANSFER, true);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return transferProfits;
    }

    /**
     * 封装省级平级利润
     * @param fromAgent
     * @param toAgent
     * @param qunantity
     * @return
     */
    public List<AccountsTransfer> LevelingProfit(Agent fromAgent,Agent toAgent,Integer qunantity){

        List<AccountsTransfer> list = new ArrayList<>();

        //todo  省级平级利润

        //todo 判断当前发货人的上级是不是省级,是就返20/盒
        Agent toAgentParent = null;
        if(toAgent.getParent().getId() != null){
            Integer toParentId2 = toAgent.getParent().getId();
            toAgentParent = agentHandler.get(toParentId2);
            AgentLevel agentLevel = agentHandler.getLevel(toAgentParent);
            if (agentLevel.getLevel() == 5) {
                Double profit1 = Double.valueOf(qunantity * 20);
                String remark3 = toAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + toAgentParent.getRealName() + "获得省级平级利润返利：" + profit1 + "元";
                AccountsTransfer transferProfits = transferProfit(fromAgent, toAgent, new Date(), new Date(), remark3, profit1, AccountsTransferStatus.TRANSFER, true);
                list.add(transferProfits);
            }
        }

        //todo 判断当前发货人的上上级是不是省级,是就返10/盒
        Agent toAgentParentUp = null;
        if(toAgentParent.getParent().getId() != null){
            Integer toAgentParentUpId = toAgentParent.getParent().getId();
            toAgentParentUp = agentHandler.get(toAgentParentUpId);
            AgentLevel agentLevelParent = agentHandler.getLevel(toAgentParentUp);
            if (agentLevelParent.getLevel() == 5) {
                Double profit2 = Double.valueOf(qunantity * 10);
                String remark4 = toAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + toAgentParentUp.getRealName() + "获得省级平级利润返利：" + profit2 + "元";
                AccountsTransfer transferProfits4 = transferProfit(fromAgent, toAgent, new Date(), new Date(), remark4, profit2, AccountsTransferStatus.TRANSFER, true);
                list.add(transferProfits4);
            }
        }

        //todo 判断当前发货人的上上上级是不是省级,是就返5/盒
        if(toAgentParentUp.getParent().getId() != null){
            Integer toAgentParentUpIds = toAgentParentUp.getParent().getId();
            Agent toAgentParentUpUp = agentHandler.get(toAgentParentUpIds);
            AgentLevel agentLevelParentUp = agentHandler.getLevel(toAgentParentUpUp);
            if (agentLevelParentUp.getLevel() == 5) {
                Double profit3 = Double.valueOf(qunantity * 5);
                String remark5 = toAgent.getRealName() + "向" + fromAgent.getRealName() + "进货" + qunantity + "盒，" + toAgentParentUpUp.getRealName() + "获得省级平级利润返利：" + profit3 + "元";
                AccountsTransfer transferProfits5 = transferProfit(fromAgent, toAgent, new Date(), new Date(), remark5, profit3, AccountsTransferStatus.TRANSFER, true);
                list.add(transferProfits5);
            }
        }
        return list;
    }










    @Autowired
    private PriceHandler priceHandler;

    //根据进货数量计算价格
    public Price purchasePrice(Goods goods, Integer qunantity){
        //根据收货人拿货数量判断收货人拿货价格
        Map map = new HashedMap();
        map.put("goods", goods);
        List<Price> prices =  priceDao.getList(map);
        List<Price> plist = new ArrayList();
        for (Price price : prices) {
            if(price.getThreshold()<=qunantity){
                plist.add(price);
            }
        }

        Price price = plist.get(0);
        for (Price price1 : plist) {
            if(price1.getThreshold()>=price.getThreshold()){
                price = price1;
            }
        }

        return price;
    }

    /**
     * 撤回奖励
     * @param fromAgent 出货人  toAgent收货人
     * @return
     */

    public List<AccountsTransfer> revokehjgnVoucher(Agent fromAgent, Agent toAgent, Goods goods, Integer qunantity) {
        List<AccountsTransfer> list = new ArrayList<>();
        Map<String,Double[]> reward = RewardUtil.getRewardStr(goods.getVoucher());

        int jingliLevel = AgentLevelEnum.JINGLIHEHUOREN.getState();  //经理合伙人的等级
        int zongjianLevel = AgentLevelEnum.ZONGJIANHEHUOREN.getState();//总监合伙人的等级
        int zongcaiLevel = AgentLevelEnum.ZONGCAIHEHUOREN.getState(); //总裁合伙人等级
        int fengongsi = AgentLevelEnum.FENGONGSIHEHUOREN.getState(); //分公司合伙人等级
        int lianchuangLevel = AgentLevelEnum.LIANCHUANG.getState();  //联创等级
        AgentLevel toAgentLevel = agentHandler.getLevel(toAgent);  //收货人的AgentLevel
        AgentLevel fromAgentLevel = agentHandler.getLevel(fromAgent);  //发货人的AgentLevel

        //一、管理员给分公司合伙人转货要给分公司合伙人团长奖励
        if (fromAgent.isMutedUser()) {
            if(toAgentLevel.getLevel()==fengongsi){

                //团长奖
                AccountsTransfer teamHead = new AccountsTransfer();
                teamHead.setFromAgent(toAgent);
                teamHead.setToAgent(fromAgent);
                teamHead.setTransferTime(new Date());
                teamHead.setStatus(AccountsTransferStatus.TRANSFER);
                teamHead.setCanShow(true);
                teamHead.setRemark("退回团长奖励");
                Double tem = PreciseComputeUtil.mul(reward.get("teamHead")[0],qunantity);
                teamHead.setAmount(tem);
                list.add(teamHead);

                //分公司合伙人招募奖
                AccountsTransfer extra = new AccountsTransfer();
                extra.setFromAgent(toAgent);
                extra.setToAgent(fromAgent);
                extra.setTransferTime(new Date());
                extra.setStatus(AccountsTransferStatus.TRANSFER);
                extra.setCanShow(true);
                extra.setRemark("退回分公司合伙人招募奖励");
                Double tem1 = PreciseComputeUtil.mul(reward.get("extra")[3],qunantity);
                extra.setAmount(tem1);
                list.add(extra);
            }
        }
        //二、非管理员转货
        //先判断收货人
        // 1、合伙人有业绩奖和平推奖
        if(toAgentLevel.getLevel()>=fengongsi && toAgentLevel.getLevel()<=jingliLevel){
            //业绩奖
            AccountsTransfer achievement = new AccountsTransfer();
            achievement.setFromAgent(toAgent);
            achievement.setToAgent(fromAgent);
            achievement.setTransferTime(new Date());
            achievement.setStatus(AccountsTransferStatus.TRANSFER);
            achievement.setCanShow(true);
            achievement.setRemark("退回合伙人业绩奖励");
            if("经理合伙人".equals(toAgent.getLevelName())){
                Double tem = PreciseComputeUtil.mul(reward.get("achievement")[0],qunantity);
                achievement.setAmount(tem);
                list.add(achievement);
            }else if("总监合伙人".equals(toAgent.getLevelName())){
                Double tem = PreciseComputeUtil.mul(reward.get("achievement")[1],qunantity);
                achievement.setAmount(tem);
                list.add(achievement);
            }else if("总裁合伙人".equals(toAgent.getLevelName())){
                Double tem = PreciseComputeUtil.mul(reward.get("achievement")[2],qunantity);
                achievement.setAmount(tem);
                list.add(achievement);
            }else if("分公司合伙人".equals(toAgent.getLevelName())){
                Double tem = PreciseComputeUtil.mul(reward.get("achievement")[3],qunantity);
                achievement.setAmount(tem);
                list.add(achievement);
            }

            //平推奖
            Double equalityTem = PreciseComputeUtil.mul(reward.get("equality")[0],qunantity);
            AccountsTransfer equality = new AccountsTransfer();
            equality.setFromAgent(toAgent);
            equality.setToAgent(fromAgent);
            equality.setTransferTime(new Date());
            equality.setStatus(AccountsTransferStatus.TRANSFER);
            equality.setCanShow(true);
            equality.setAmount(equalityTem);
            equality.setRemark("退回平推奖励");
            list.add(equality);

            //招募奖,直接上级不是发货人
            Agent parent = toAgent.getParent();

            if(!fromAgent.getAgentCode().equals(parent.getAgentCode())){  //直接上级不是发货人

                AgentLevel parentLevel = agentHandler.getLevel(parent);  //收货人上级的AgentLevel

                AccountsTransfer extra = new AccountsTransfer();
                extra.setFromAgent(parent);
                extra.setToAgent(fromAgent);
                extra.setTransferTime(new Date());
                extra.setStatus(AccountsTransferStatus.TRANSFER);
                extra.setCanShow(true);
                extra.setRemark("退回合伙人招募奖励");

                if("经理合伙人".equals(parentLevel.getName())){
                    Double tem1 = PreciseComputeUtil.mul(reward.get("extra")[0],qunantity);
                    extra.setAmount(tem1);
                    list.add(extra);
                }

                if("总监合伙人".equals(parentLevel.getName())
                        && toAgentLevel.getLevel()>=zongcaiLevel && toAgentLevel.getLevel()<=zongjianLevel)
                {
                    Double tem1 = PreciseComputeUtil.mul(reward.get("extra")[1],qunantity);
                    extra.setAmount(tem1);
                    list.add(extra);
                }

                if("总裁合伙人".equals(parentLevel.getName()) && toAgentLevel.getLevel()==zongcaiLevel){
                    Double tem1 = PreciseComputeUtil.mul(reward.get("extra")[2],qunantity);
                    extra.setAmount(tem1);
                    list.add(extra);
                }

            }


        }

        // 2、联创的平推奖，合伙人给联创发货，联创的上级是联创
        if(fromAgentLevel.getLevel()>=zongcaiLevel && fromAgentLevel.getLevel()<=jingliLevel){
            Agent parent = toAgent.getParent();
            if(!fromAgent.getAgentCode().equals(parent.getAgentCode())) {  //直接上级不是发货人
                AgentLevel parentLevel = agentHandler.getLevel(parent);  //收货人上级的AgentLevel
                if(toAgentLevel.getLevel()==lianchuangLevel && parentLevel.getLevel()==lianchuangLevel){
                    //平推奖
                    Double equalityTem = PreciseComputeUtil.mul(reward.get("equality")[0],qunantity);
                    AccountsTransfer equality = new AccountsTransfer();
                    equality.setFromAgent(parent);
                    equality.setToAgent(fromAgent);
                    equality.setTransferTime(new Date());
                    equality.setStatus(AccountsTransferStatus.TRANSFER);
                    equality.setCanShow(true);
                    equality.setAmount(equalityTem);
                    equality.setRemark("退回平推奖励");
                    list.add(equality);
                }
            }

        }

        return list;
    }


    private final String[] levelNames = {"VIP", "市代", "省代", "大区", "董事", "金董", "分公司", "联盟单位"};
//
    private final Integer[] paySum = {310, 2500, 4200, 16000, 32000, 64000, 128000, 1000000000};
//
    private final Double[] vipPercent = {0.05, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5, 0.6};
//
    private final Double[] basePercent = {0.3, 0.05, 0.05};


    //获取该拿多少百分比
    private Double getVipPerCent(Agent agent) {
        //暂时返回0
            return 0.0;
//        System.out.println(agent.getRealName()+"===");
//        Double payBalance = agent.getAccounts().getAccount(AccountsType.CONSUME);//消费金额
//        if (payBalance == null) payBalance = 0.0;
//        //如果不是游客
//        if (agent.getAgentCode() != null) {
//            String levelName = agentHandler.getLevel(agent).getName();
//            //不是亲情价
//            //如果是联盟单位
//            if (levelName.equals("联盟单位")) {
//                return vipPercent[vipPercent.length - 1];//返回最后一个百分比
//            }
//            //如果不是联盟单位 获取级别对用的消费
//            Integer index = getIndexFromArray(levelNames, levelName);
//            if (index < paySum.length && index > -1) {
//                payBalance += paySum[index];
//            }
//        }
//        //获取对应消费对应的获得奖励百分比
//        for (int i = 0; i < paySum.length; i++) {
//            if (payBalance < paySum[i]) {
//                Integer ii = i - 1;
//                if (ii < 0) {
//                    return 0.0;
//                } else {
//                    return vipPercent[ii];
//                }
//            }
//        }
//        return vipPercent[vipPercent.length - 1];
    }


    /**
     * 从数组中获取对应位置
     *
     * @param objects
     * @param o
     * @return
     */
    private Integer getIndexFromArray(Object[] objects, Object o) {
        for (int i = 0; i < objects.length; i++) {
            if (o.equals(objects[i])) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 从数组中获取对应区间
     *
     * @param objects
     * @param o
     * @return
     */
    private Integer getIndexFromArray(Integer[] objects, Object o) {
        for (int i = 0; i < objects.length; i++) {
            if (o.equals(objects[i])) {
                return i;
            }
        }
        return -1;
    }


    public static void main(String[] args) {
        System.out.println(2.2 / 2);
        final String[] levelNames = {"VIP", "市代", "省代", "大区", "董事", "金董", "分公司", "联盟单位"};

        final Integer[] paySum = {310, 2500, 4200, 16000, 32000, 64000, 128000, 1000000000};

        final Double[] percent = {0.05, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5, 0.6};

        Double payBalance = 1222222.0;//消费金额
        if (payBalance == null) payBalance = 2200.0;
        //如果不是游客
        if (true) {
            String levelName = "金董";
            //不是亲情价
            //如果是联盟单位
            if (levelName.equals("联盟单位")) {
                System.out.println(percent[percent.length - 1]);
                return;
            }
            //如果不是联盟单位 获取级别对用的消费
            Integer index = new AccountsHandlerImpl().getIndexFromArray(levelNames, levelName);
            System.out.println(index);
            if (index < paySum.length && index > -1) {
                payBalance += paySum[index];
                System.out.println(payBalance);
            }
        }
        //获取对应消费对应的获得奖励百分比
        for (int i = 0; i < paySum.length; i++) {
            if (payBalance < paySum[i]) {
                Integer ii = i - 1;
                if (ii < 0) {
                    System.out.println(0.0);
                    return;
                } else {
                    System.out.println(ii);
                    System.out.println(percent[ii]);
                    return;
                }
            }
        }
        System.out.println(percent[percent.length - 1]);



    }

    private AccountsDao accountsDao;

    @Autowired
    private GoodsAccountHandler goodsAccountHandler;

    @Autowired
    private AgentHandler agentHandler;

    @Autowired
    private AgentLevelHandler agentLevelHandler;

    private AccountsRecordHandler accountsRecordHandler;
    public AccountsDao getAccountsDao() {
        return accountsDao;
    }

    @Autowired
    private TransferHandler transferHandler;

    @Autowired
    public void setAccountsDao(AccountsDao accountsDao) {
        this.accountsDao = accountsDao;
        super.setBaseDao(accountsDao);
    }

    @Autowired
    private PriceDao priceDao;

}
